package cn.jaye.fabric.application;

import cn.jaye.fabric.common.constant.MicroConstant;
import cn.jaye.fabric.domain.model.Api;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.jaye.fabric.application.command.ListApiCommand;
import cn.jaye.fabric.domain.service.RestTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jaye
 * @create 2017-12-27 10:18
 */
@Service
public class ApiApplicationService {

    @Autowired
    private RestTemplateService restTemplateService;

    @Autowired
    private MicroConstant microConstant;


    private static final String APIAUTHORIZE_SERVICE_NAME = "apiauthorize";

    public String importRaml(String serviceId, File file) {
        try {
            String encoding = "UTF-8";
            if (file.isFile() && file.exists()) { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                boolean flag = false;
                int i = 0;
                List<Api> apiList = new ArrayList<>();
                Api api = new Api();
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    if (lineTxt.startsWith("#") && !lineTxt.contains("RAML")) {
                        String apiName = lineTxt.substring(1, lineTxt.length());
                        api.setApiName(apiName);
                    }
                    if (lineTxt.startsWith("/") && lineTxt.endsWith(":")) {
                        String apiUrl = lineTxt.substring(0, lineTxt.length() - 1);
                        api.setUrl(apiUrl);
                        Api resApi = new Api();
                        resApi.setServiceId(serviceId);
                        resApi.setUrl(api.getUrl());
                        resApi.setApiName(api.getApiName());
                        apiList.add(resApi);
                        continue;
                    }
                }
                read.close();
                /**
                 * 调用接口导入api列表
                 */
                if (apiList != null && apiList.size() > 0) {
                    return importApis(apiList);
                }
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return null;
    }

    private String importApis(List<Api> apiList) {
        String url = microConstant.getApiGatewayAddress() + APIAUTHORIZE_SERVICE_NAME + "/api/create";
        JSONObject postData = new JSONObject();
        postData.put("apis", apiList);
        JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
        return JSON.toJSONString(resultObject);
    }

    public JSONObject listApi(ListApiCommand listApiCommand) {
        String url = microConstant.getApiGatewayAddress() + APIAUTHORIZE_SERVICE_NAME + "/api/list";
        JSONObject postData = new JSONObject();
        JSONObject pageData = new JSONObject();
        if (listApiCommand.getSizes() != null) {
            pageData.put("sizes", listApiCommand.getSizes());
        }
        if (listApiCommand.getCurrentPage() != null) {
            pageData.put("currentPage", listApiCommand.getCurrentPage());
        }
        postData.put("page", pageData);
        if (StringUtils.isNotBlank(listApiCommand.getCondition())) {
            postData.put("apiName", listApiCommand.getCondition());
            postData.put("apiId", listApiCommand.getCondition());
            postData.put("url", listApiCommand.getCondition());
            postData.put("serviceId", listApiCommand.getCondition());
            postData.put("serviceName", listApiCommand.getCondition());
            postData.put("serviceNameCn", listApiCommand.getCondition());

        }
        JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
        return resultObject;
    }

    public String listAllApi() {
        String url = microConstant.getApiGatewayAddress() + APIAUTHORIZE_SERVICE_NAME + "/api/query";
        JSONObject postData = new JSONObject();
        JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
        return JSON.toJSONString(resultObject);
    }
}
